<script setup>
import { onMounted, ref, computed } from 'vue'
import { useRpaStore } from '@/stores/rpa'
import { Loading, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CommonPagination from '@/components/CommonPagination.vue'
import { formatDateTime } from '@/utils/dateFormat'

const rpaStore = useRpaStore()
const currentPage = ref(1)
const pageSize = ref(15)
const dialogVisible = ref(false)
const currentAction = ref('')
const actionResult = ref({})
const actionLoading = ref(false)
const editDialogVisible = ref(false)
const currentRow = ref(null)

onMounted(() => {
  rpaStore.fetchApps()
})

// Compute paginated data
const paginatedApps = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return rpaStore.apps.slice(start, end)
})

// Calculate total pages
const total = computed(() => rpaStore.apps.length)

// Handle page change
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 添加应用
const handleAddApp = () => {
  editForm.value = {
    id: '',
    name: '新建应用',
    description: '请输入应用描述',
    type: 'Web自动化',
    status: '已停止'
  }
  
  currentAction.value = '添加应用'
  editDialogVisible.value = true
}

// 查看应用详情
const handleViewApp = (app) => {
  actionLoading.value = true
  currentAction.value = '查看应用详情'
  currentRow.value = app
  
  // 模拟API调用
  setTimeout(() => {
    actionResult.value = {
      success: true,
      message: '获取应用详情成功',
      data: {
        ...app,
        detailedInfo: {
          creator: '管理员',
          version: '1.0.3',
          lastModified: new Date().toLocaleString('zh-CN', { 
            year: 'numeric', month: '2-digit', day: '2-digit',
            hour: '2-digit', minute: '2-digit', second: '2-digit',
            hour12: false
          }),
          configuration: {
            maxThreads: 4,
            timeout: '30分钟',
            autoRetry: true,
            notifyOnCompletion: true
          },
          compatibleRobots: ['通用机器人', '专用OCR机器人'],
          dependencies: ['数据抓取模块', 'PDF解析插件']
        }
      }
    }
    actionLoading.value = false
    dialogVisible.value = true
  }, 800)
}

// 编辑应用
const handleEditApp = (app) => {
  editForm.value = {
    id: app.id || '',
    name: app.name || '',
    description: app.description || '',
    type: app.type || '',
    status: app.status || '已停止'
  }
  
  currentAction.value = '编辑应用'
  editDialogVisible.value = true
}

// 表单数据
const editForm = ref({
  id: '',
  name: '',
  description: '',
  type: '',
  status: ''
})

// 提交编辑表单
const submitEditForm = () => {
  actionLoading.value = true
  
  // 模拟API调用
  setTimeout(() => {
    actionResult.value = {
      success: true,
      message: '应用编辑成功',
      data: {
        appId: editForm.value.id,
        name: editForm.value.name,
        description: editForm.value.description,
        type: editForm.value.type,
        status: editForm.value.status,
        updatedAt: formatDateTime(new Date()),
        changes: ['更新了应用信息']
      }
    }
    actionLoading.value = false
    editDialogVisible.value = false
    dialogVisible.value = true
    
    ElMessage({
      type: 'success',
      message: `应用 ${editForm.value.name} 编辑成功`
    })
  }, 800)
}

// 取消编辑
const cancelEdit = () => {
  editDialogVisible.value = false
  ElMessage({
    type: 'info',
    message: '已取消编辑'
  })
}

// 在需要格式化时间的地方使用formatDateTime
const formatDate = (date) => {
  return formatDateTime(date)
}
</script>

<template>
  <el-card class="app-list-card">
    <template #header>
      <div class="app-list-header">
        <div class="app-list-title">
          <el-button type="primary" @click="handleAddApp">
            <el-icon style="margin-right: 5px;"><Plus /></el-icon>添加机应用
          </el-button>
        </div>
      </div>
    </template>
    
    <div class="card-body">
      <!-- Loading spinner -->
      <div v-if="rpaStore.loading" class="loading-container">
        <el-icon class="is-loading"><loading /></el-icon>
        <span class="loading-text">加载中...</span>
      </div>
      
      <!-- Error message -->
      <el-alert
        v-if="rpaStore.error"
        :title="rpaStore.error"
        type="error"
        show-icon
      />
      
      <!-- RPA Applications Table -->
      <div v-else class="table-container">
        <el-table :data="paginatedApps" style="width: 100%" :max-height="600">
          <el-table-column prop="name" label="应用名称" />
          <el-table-column prop="description" label="描述" />
          <el-table-column prop="type" label="类型" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === '运行中' ? 'success' : 
                scope.row.status === '已停止' ? 'info' : 'danger'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="updatedAt" label="更新时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.updatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="145" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="handleViewApp(scope.row)"
                  :loading="actionLoading && currentAction === '查看应用详情' && scope.row === currentRow"
                >查看</el-button>
                <el-button 
                  type="warning" 
                  size="small"
                  @click="handleEditApp(scope.row)"
                >编辑</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- Pagination -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :page-sizes="[10, 15, 20, 50]"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
        @size-change="size => { pageSize = size; currentPage = 1; }"
        prev-text="上一页"
        next-text="下一页"
        :pager-count="5"
      />
    </div>
  </el-card>

  <!-- 操作结果展示对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="currentAction + '结果'"
    width="50%"
    :append-to-body="true"
    :top="'10vh'"
  >
    <div v-if="actionResult.success" class="action-result">
      <el-alert
        title="操作成功"
        type="success"
        :description="actionResult.message"
        show-icon
        :closable="false"
        class="result-alert"
      />
      
      <div class="result-data">
        <h4>响应数据:</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item 
            v-for="(value, key) in actionResult.data" 
            :key="key" 
            :label="key"
          >
            <span v-if="typeof value !== 'object'">{{ value }}</span>
            <div v-else>
              <div v-for="(subVal, subKey) in value" :key="subKey">
                <strong>{{ subKey }}:</strong> 
                <span v-if="!Array.isArray(subVal)">{{ subVal }}</span>
                <div v-else>
                  <ul>
                    <li v-for="(item, idx) in subVal" :key="idx">{{ item }}</li>
                  </ul>
                </div>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
    
    <div v-else class="action-result">
      <el-alert
        title="操作失败"
        type="error"
        :description="actionResult.message"
        show-icon
        :closable="false"
        class="result-alert"
      />
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑应用对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    :title="currentAction === '添加应用' ? '添加应用' : '编辑应用'"
    width="50%"
    :append-to-body="true"
    :top="'10vh'"
  >
    <el-form :model="editForm" label-width="120px">
      <el-form-item label="应用名称">
        <el-input v-model="editForm.name" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="editForm.description" type="textarea" rows="3" />
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="editForm.type" placeholder="请选择类型" style="width: 100%">
          <el-option label="Web自动化" value="Web自动化" />
          <el-option label="桌面自动化" value="桌面自动化" />
          <el-option label="API自动化" value="API自动化" />
          <el-option label="数据处理" value="数据处理" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
          <el-option label="运行中" value="运行中" />
          <el-option label="已停止" value="已停止" />
          <el-option label="异常" value="异常" />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="submitEditForm" :loading="actionLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.app-list-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 调整卡片头部内边距 */
:deep(.el-card__header) {
  padding: 10px 20px;  /* 将默认的 20px 内边距减半为 10px */
}

.card-body {
  flex: 1;
  overflow: auto;
  position: relative;
  padding: 6px 0 70px 0;
}

.table-container {
  height: 100%;
  overflow: auto;
}

.app-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0;
}

.app-list-title {
  display: flex;
  align-items: center;
}

/* 优化添加按钮样式 */
.app-list-title .el-button {
  padding: 8px 16px;
  height: 32px;
  line-height: 1;
}

.app-list-title .el-button .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.loading-container .el-icon {
  font-size: 2rem;
  margin-bottom: 10px;
}

.loading-text {
  color: #909399;
}

.pagination-container {
  position: absolute;
  bottom: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 15px 0;
  background-color: white;
  z-index: 10;
}

.action-result {
  padding: 10px;
}

.result-alert {
  margin-bottom: 20px;
}

.result-data {
  margin-top: 20px;
}

.result-data h4 {
  margin-bottom: 10px;
  color: #606266;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 2px;
  flex-wrap: nowrap;
  white-space: nowrap;
  overflow-x: auto;
}

.action-buttons::-webkit-scrollbar {
  display: none;
}

.action-buttons {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.action-buttons .el-button--small {
  padding: 5px 10px;
  font-size: 12px;
  height: 28px;
  line-height: 1;
  margin-left: 0;
  margin-right: 3px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 调整表格容器样式 */
.el-card {
  margin-top: 6px;
}

/* 移除表格上方的多余空间 */
.el-table {
  margin-top: 0;
}
</style> 